<template>
  <div class="home">
    <!-- <el-card style="margin-bottom: 20px">
      <el-row :gutter="20" align="middle">
        <el-col :span="18">
          <el-input
            v-model="search"
            size="large"
            placeholder="Please Input"
            :suffix-icon="Search"
          />
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button @click="addTask">新 建</el-button>
        </el-col>
      </el-row>
    </el-card> -->
    <el-card>
      <div style="display: flex; justify-content: space-between">
        <el-tabs type="card" v-model.number="queryParameter.status">
          <el-tab-pane label="待办" :name="0"></el-tab-pane>
          <el-tab-pane label="进行中" :name="1"></el-tab-pane>
          <el-tab-pane label="删除" :name="2"></el-tab-pane>
        </el-tabs>
        <el-button @click="addTask">新 建</el-button>
        <el-button @click="logout">退出登录</el-button>
      </div>
      <el-table :data="taskList" style="width: 100%">
        <el-table-column label="标题" prop="title" min-width="120" />
        <el-table-column label="内容" prop="content" min-width="200" />
        <el-table-column label="状态" prop="status">
          <template #default="{ row }" min-width="80">
            <el-tag type="warning" v-if="row.status === 0">待办</el-tag>
            <el-tag type="success" v-else-if="row.status === 1">进行中</el-tag>
            <el-tag type="danger" v-else-if="row.status === 2">完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否重要" prop="is_major" min-width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_major"
              :inactive-value="0"
              :inactive-action-icon="Star"
              :active-value="1"
              :active-action-icon="StarFilled"
              @change="changeIsMajor(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="start_time" min-width="120" />
        <el-table-column label="结束时间" prop="expire_time" min-width="120" />
        <el-table-column label="操作" align="right" min-width="120">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        v-show="total"
        background
        :total="total"
        v-model:page-size="queryParameter.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        v-model:current-page="queryParameter.currentPage"
        layout="total, sizes, prev, pager, next"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script lang="ts" setup name="Home">
import type { Task } from "@/api/interface/index.ts";
import { ElMessage, dayjs } from "element-plus";
import { StarFilled, Star } from "@element-plus/icons-vue";
import { ref, onMounted, watch } from "vue";
import {
  reqSelectTask,
  reqDeleteTask,
  // reqUpdateTaskStatus,
  reqUpdateTaskMajor
} from "@/api/task";
import { reqUserLogout } from "@/api/user";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/modules/user";

const userStore = useUserStore();
const router = useRouter();

onMounted(() => {
  getTaskList();
});
// const search = ref("");

let total: number = 0;
let queryParameter = ref({
  currentPage: 1,
  pageSize: 10,
  status: 0 as 0 | 1 | 2
});
watch(
  queryParameter,
  () => {
    getTaskList();
    console.log(queryParameter.value);
  },
  {
    deep: true
  }
);

let taskList = ref<Task.TaskItem[]>([
  // {
  //   id: 49,
  //   title: "代号",
  //   content: "今晚打老虎",
  //   status: 1,
  //   is_major: 1,
  //   start_time: "2023-10-30T12:54:22.000Z",
  //   expire_time: "2023-11-11T12:54:22.000Z"
  // }
]);
/**
 * 查询任务
 */
async function getTaskList() {
  try {
    let result = await reqSelectTask(queryParameter.value);
    taskList.value =
      result.data?.map((item) => {
        console.log(item.start_time);

        item.start_time = dayjs(item.start_time).format("YYYY-MM-DD HH:mm:ss");
        item.expire_time = dayjs(item.expire_time).format("YYYY-MM-DD HH:mm:ss");
        return item;
      }) || [];
    total = result.total || 0;
    // Object.assign(queryParameter.value, { total, pageSize, currentPage });
  } catch (error) {
    console.log(error);
  }
}

const addTask = () => {
  router.push({
    path: "/home/action-task",
    query: {
      title: "add"
    }
  });
};

/**
 * 点击编辑 跳转
 * @param row 任务项
 */
const handleEdit = (row: Task.TaskItem) => {
  router.push({
    path: "/home/action-task",
    query: {
      title: "edit",
      id: row.id,
      row: JSON.stringify(row)
    }
  });
};

/**
 * 点击删除
 * @param row
 */
const handleDelete = async (row: Task.TaskItem) => {
  reqDeleteTask({ ids: [row.id!] })
    .then((res) => {
      if (res.code === 200) ElMessage.success("删除成功");
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      getTaskList();
    });
};

/**
 * 设置是否重要
 * @param row
 */
const changeIsMajor = async (row: Task.TaskItem) => {
  try {
    await reqUpdateTaskMajor({
      id: row.id!,
      is_major: row.is_major
    });
    ElMessage.success("修改成功");
  } catch (error) {
    console.log(error);
  }
};

/**
 * 点击退出登录
 */
const logout = async () => {
  try {
    let result = await reqUserLogout();
    console.log(result);
    router.push("/login");
    ElMessage.success("退出成功");
    userStore.setToken({
      access_token: "",
      username: "",
      refresh_token: ""
    });
  } catch (error) {
    console.log(error);
  }
};
</script>

<style lang="scss" scoped></style>
